import React, { useState, useEffect } from 'react'
import {
  Card,
  Upload,
  Button,
  Select,
  Form,
  message,
  Progress,
  Table,
  Space,
  Tag,
  Modal,
  Typography,
  Alert,
  List,
  Divider,
  Row,
  Col,
  Statistic
} from 'antd'
import {
  InboxOutlined,
  CloudUploadOutlined,
  EyeOutlined,
  StopOutlined,
  ReloadOutlined,
  DownloadOutlined,
  DeleteOutlined
} from '@ant-design/icons'
import { WideTable } from '@/types/index'
import { request } from '@/services/api'
import type { UploadProps } from 'antd/es'
import type { ColumnsType } from 'antd/es/table'

const { Dragger } = Upload
const { Option } = Select
const { Text, Title } = Typography

interface ImportTask {
  taskId: string
  status: 'PENDING' | 'RUNNING' | 'COMPLETED' | 'FAILED' | 'CANCELLED'
  progress: number
  totalRows: number
  processedRows: number
  successRows: number
  errorRows: number
  errorMessage?: string
  startTime: string
  endTime?: string
  errorDetails: string[]
  wideTableName?: string
}

interface ImportForm {
  wideTableId: number
  file: File
}

const ExcelImport: React.FC = () => {
  const [form] = Form.useForm<ImportForm>()
  const [loading, setLoading] = useState(false)
  const [wideTableList, setWideTableList] = useState<WideTable[]>([])
  const [importTasks, setImportTasks] = useState<ImportTask[]>([])
  const [currentTask, setCurrentTask] = useState<ImportTask | null>(null)
  const [taskModalVisible, setTaskModalVisible] = useState(false)
  const [errorModalVisible, setErrorModalVisible] = useState(false)
  const [selectedErrors, setSelectedErrors] = useState<string[]>([])
  const [fileList, setFileList] = useState<any[]>([])
  const [pollInterval, setPollInterval] = useState<NodeJS.Timeout | null>(null)
  
  // 获取离线宽表列表
  const fetchOfflineWideTables = async () => {
    try {
      const response = await request.get<WideTable[]>('/wide-tables', {
        type: 'OFFLINE',
        status: 'ACTIVE'
      })
      setWideTableList(response.data)
    } catch (error) {
      message.error('获取宽表列表失败')
    }
  }
  
  // 获取导入任务列表
  const fetchImportTasks = async () => {
    try {
      const response = await request.get<ImportTask[]>('/excel-import/tasks')
      setImportTasks(response.data)
    } catch (error) {
      console.error('获取任务列表失败:', error)
    }
  }
  
  // 轮询任务状态
  const pollTaskStatus = (taskId: string) => {
    const interval = setInterval(async () => {
      try {
        const response = await request.get<ImportTask>(`/excel-import/tasks/${taskId}/status`)
        const task = response.data
        
        setImportTasks(prev => prev.map(t => t.taskId === taskId ? task : t))
        
        if (currentTask?.taskId === taskId) {
          setCurrentTask(task)
        }
        
        // 任务完成或失败时停止轮询
        if (['COMPLETED', 'FAILED', 'CANCELLED'].includes(task.status)) {
          clearInterval(interval)
          setPollInterval(null)
          
          if (task.status === 'COMPLETED') {
            message.success('导入完成！')
          } else if (task.status === 'FAILED') {
            message.error('导入失败：' + task.errorMessage)
          }
        }
      } catch (error) {
        console.error('轮询任务状态失败:', error)
        clearInterval(interval)
        setPollInterval(null)
      }
    }, 2000)
    
    setPollInterval(interval)
  }
  
  // 文件上传配置
  const uploadProps: UploadProps = {
    name: 'file',
    multiple: false,
    accept: '.xlsx,.xls',
    fileList,
    beforeUpload: (file) => {
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                     file.type === 'application/vnd.ms-excel'
      if (!isExcel) {
        message.error('只能上传Excel文件！')
        return false
      }
      
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        message.error('文件大小不能超过10MB！')
        return false
      }
      
      setFileList([file])
      form.setFieldsValue({ file })
      return false // 阻止自动上传
    },
    onRemove: () => {
      setFileList([])
      form.setFieldsValue({ file: undefined })
    }
  }
  
  // 开始导入
  const handleImport = async (values: ImportForm) => {
    if (!values.file) {
      message.error('请选择要导入的Excel文件')
      return
    }
    
    setLoading(true)
    const formData = new FormData()
    formData.append('file', values.file)
    formData.append('wideTableId', values.wideTableId.toString())
    
    try {
      const response = await request.upload<string>('/excel-import/start', formData)
      
      const taskId = response.data
      message.success('导入任务已启动，任务ID: ' + taskId)
      
      // 重置表单
      form.resetFields()
      setFileList([])
      
      // 开始轮询任务状态
      pollTaskStatus(taskId)
      
      // 刷新任务列表
      setTimeout(fetchImportTasks, 1000)
      
    } catch (error) {
      message.error('启动导入任务失败')
    } finally {
      setLoading(false)
    }
  }
  
  // 取消任务
  const handleCancelTask = async (taskId: string) => {
    try {
      await request.post(`/excel-import/tasks/${taskId}/cancel`)
      message.success('任务已取消')
      fetchImportTasks()
    } catch (error) {
      message.error('取消任务失败')
    }
  }
  
  // 查看任务详情
  const handleViewTask = (task: ImportTask) => {
    setCurrentTask(task)
    setTaskModalVisible(true)
  }
  
  // 查看错误详情
  const handleViewErrors = (errors: string[]) => {
    setSelectedErrors(errors)
    setErrorModalVisible(true)
  }
  
  // 任务表格列定义
  const taskColumns: ColumnsType<ImportTask> = [
    {
      title: '任务ID',
      dataIndex: 'taskId',
      key: 'taskId',
      width: 150,
      ellipsis: true
    },
    {
      title: '宽表名称',
      dataIndex: 'wideTableName',
      key: 'wideTableName',
      width: 150,
      ellipsis: true
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => {
        const statusConfig = {
          PENDING: { color: 'default', text: '等待中' },
          RUNNING: { color: 'processing', text: '进行中' },
          COMPLETED: { color: 'success', text: '已完成' },
          FAILED: { color: 'error', text: '失败' },
          CANCELLED: { color: 'warning', text: '已取消' }
        }
        const config = statusConfig[status as keyof typeof statusConfig]
        return <Tag color={config.color}>{config.text}</Tag>
      }
    },
    {
      title: '进度',
      dataIndex: 'progress',
      key: 'progress',
      width: 120,
      render: (progress: number, record: ImportTask) => (
        <Progress
          percent={progress}
          size="small"
          status={record.status === 'FAILED' ? 'exception' : undefined}
        />
      )
    },
    {
      title: '总行数',
      dataIndex: 'totalRows',
      key: 'totalRows',
      width: 80,
      render: (count: number) => count ? count.toLocaleString() : '-'
    },
    {
      title: '成功/错误',
      key: 'result',
      width: 100,
      render: (_, record: ImportTask) => (
        <span>
          <Text type="success">{record.successRows || 0}</Text>
          <Divider type="vertical" />
          <Text type="danger">{record.errorRows || 0}</Text>
        </span>
      )
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      key: 'startTime',
      width: 150,
      ellipsis: true
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      fixed: 'right',
      render: (_, record: ImportTask) => (
        <Space size="small">
          <Button
            type="text"
            icon={<EyeOutlined />}
            onClick={() => handleViewTask(record)}
          >
            详情
          </Button>
          {record.status === 'RUNNING' && (
            <Button
              type="text"
              danger
              icon={<StopOutlined />}
              onClick={() => handleCancelTask(record.taskId)}
            >
              取消
            </Button>
          )}
          {record.errorRows > 0 && (
            <Button
              type="text"
              onClick={() => handleViewErrors(record.errorDetails)}
            >
              错误
            </Button>
          )}
        </Space>
      )
    }
  ]
  
  useEffect(() => {
    fetchOfflineWideTables()
    fetchImportTasks()
    
    return () => {
      if (pollInterval) {
        clearInterval(pollInterval)
      }
    }
  }, [])
  
  return (
    <div>
      {/* 页面头部 */}
      <div style={{ marginBottom: 24 }}>
        <Title level={2}>Excel文件导入</Title>
        <Text type="secondary">支持导入Excel文件到离线数据宽表，文件大小限制10MB</Text>
      </div>
      
      {/* 导入表单 */}
      <Card title="导入配置" style={{ marginBottom: 24 }}>
        <Form
          form={form}
          layout="vertical"
          onFinish={handleImport}
        >
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="wideTableId"
                label="目标宽表"
                rules={[{ required: true, message: '请选择目标宽表' }]}
              >
                <Select placeholder="请选择离线宽表" showSearch>
                  {wideTableList.map(table => (
                    <Option key={table.id} value={table.id}>
                      {table.displayName} ({table.name})
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="file"
                label="Excel文件"
                rules={[{ required: true, message: '请选择Excel文件' }]}
              >
                <Dragger {...uploadProps} style={{ padding: '20px 0' }}>
                  <p className="ant-upload-drag-icon">
                    <InboxOutlined />
                  </p>
                  <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
                  <p className="ant-upload-hint">支持 .xlsx .xls 格式，文件大小不超过10MB</p>
                </Dragger>
              </Form.Item>
            </Col>
          </Row>
          
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              icon={<CloudUploadOutlined />}
              size="large"
            >
              开始导入
            </Button>
          </Form.Item>
        </Form>
      </Card>
      
      {/* 任务列表 */}
      <Card
        title="导入任务"
        extra={
          <Button
            icon={<ReloadOutlined />}
            onClick={fetchImportTasks}
          >
            刷新
          </Button>
        }
      >
        <Table
          columns={taskColumns}
          dataSource={importTasks}
          rowKey="taskId"
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 个任务`
          }}
          scroll={{ x: 1000 }}
        />
      </Card>
      
      {/* 任务详情模态框 */}
      <Modal
        title="任务详情"
        open={taskModalVisible}
        onCancel={() => setTaskModalVisible(false)}
        footer={null}
        width={800}
      >
        {currentTask && (
          <div>
            <Row gutter={16} style={{ marginBottom: 24 }}>
              <Col span={6}>
                <Statistic title="任务ID" value={currentTask.taskId} />
              </Col>
              <Col span={6}>
                <Statistic title="总行数" value={currentTask.totalRows} />
              </Col>
              <Col span={6}>
                <Statistic title="成功行数" value={currentTask.successRows} valueStyle={{ color: '#3f8600' }} />
              </Col>
              <Col span={6}>
                <Statistic title="错误行数" value={currentTask.errorRows} valueStyle={{ color: '#cf1322' }} />
              </Col>
            </Row>
            
            <Progress
              percent={currentTask.progress}
              status={currentTask.status === 'FAILED' ? 'exception' : undefined}
              style={{ marginBottom: 16 }}
            />
            
            <div style={{ marginBottom: 16 }}>
              <Text strong>开始时间：</Text>
              <Text>{currentTask.startTime}</Text>
            </div>
            
            {currentTask.endTime && (
              <div style={{ marginBottom: 16 }}>
                <Text strong>结束时间：</Text>
                <Text>{currentTask.endTime}</Text>
              </div>
            )}
            
            {currentTask.errorMessage && (
              <Alert
                message="错误信息"
                description={currentTask.errorMessage}
                type="error"
                style={{ marginBottom: 16 }}
              />
            )}
            
            {currentTask.errorDetails.length > 0 && (
              <div>
                <Text strong>错误详情：</Text>
                <List
                  size="small"
                  dataSource={currentTask.errorDetails.slice(0, 10)}
                  renderItem={item => (
                    <List.Item>
                      <Text type="danger">{item}</Text>
                    </List.Item>
                  )}
                  style={{ maxHeight: 200, overflow: 'auto', marginTop: 8 }}
                />
                {currentTask.errorDetails.length > 10 && (
                  <Text type="secondary">... 还有 {currentTask.errorDetails.length - 10} 个错误</Text>
                )}
              </div>
            )}
          </div>
        )}
      </Modal>
      
      {/* 错误详情模态框 */}
      <Modal
        title="错误详情"
        open={errorModalVisible}
        onCancel={() => setErrorModalVisible(false)}
        footer={null}
        width={600}
      >
        <List
          size="small"
          dataSource={selectedErrors}
          renderItem={(item, index) => (
            <List.Item>
              <Text>{index + 1}. {item}</Text>
            </List.Item>
          )}
          style={{ maxHeight: 400, overflow: 'auto' }}
        />
      </Modal>
    </div>
  )
}

export default ExcelImport